import { errMsg } from "../err-msg";
import { SystemJS } from "../s";
import { BASE_URL, IMPORT_MAP } from "../common";
var jsContentTypeRegEx = /^(text|application)\/(x-)?javascript(;|$)/;

export const instantiate = async function (
    this: SystemJS,
    url: string,
    parent?: string
) {
    var loader = this;
    if (!this.fetch) {
        throw new Error("We can't get fetch in System or globalThis! ");
    }
    /** 因为 经过了 resolve，所以不需要进行 url 操作 */
    const res = await this.fetch(url, {
        credentials: "same-origin",
        integrity: this[IMPORT_MAP].integrity[url],
    });
    if (!res.ok)
        throw Error(
            errMsg(
                7,
                process.env.SYSTEM_PRODUCTION
                    ? [res.status, res.statusText, url, parent].join(", ")
                    : res.status +
                          " " +
                          res.statusText +
                          ", loading " +
                          url +
                          (parent ? " from " + parent : "")
            )
        );
    var contentType = res.headers.get("content-type");
    if (!contentType || !jsContentTypeRegEx.test(contentType))
        throw Error(
            errMsg(
                4,
                process.env.SYSTEM_PRODUCTION
                    ? contentType
                    : 'Unknown Content-Type "' +
                          contentType +
                          '", loading ' +
                          url +
                          (parent ? " from " + parent : "")
            )
        );
    let source = await res.text();
    if (source.indexOf("//# sourceURL=") < 0)
        source += "\n//# sourceURL=" + url;
    //! 使用 eval 直接使用代码

    (0, eval)(source);

    return loader.getRegister(url);
};
